package com.dongbo.recorder.screenrecord.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.CSJAdError;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.CSJSplashCloseType;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.Constants;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.SplashCardManager;
import com.dongbo.recorder.screenrecord.SplashClickEyeManager;
import com.dongbo.recorder.screenrecord.TTAdManagerHolder;
import com.dongbo.recorder.screenrecord.bean.ADVBean;
import com.dongbo.recorder.screenrecord.bean.NetResponse;
import com.dongbo.recorder.screenrecord.utils.Tt;
import com.dongbo.recorder.screenrecord.utils.UIUtils;
import com.dongbo.recorder.screenrecord.widget.AgreementDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 开屏广告Activity示例
 */
public class SplashActivity extends AppCompatActivity {

    private static final String TAG = "SplashActivity_开屏";

    private TTAdNative mTTAdNative;
    private FrameLayout mSplashContainer;
    private int height;
    private int width;

    //是否强制跳转到主页面
    private boolean mForceGoMain;

    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 3000;
    private String mCodeId = "";
    private boolean mIsExpress = false; //是否请求模板广告

    private boolean mIsHalfSize = false;//是否是半全屏开屏
    private boolean mIsSplashClickEye = false;//是否是开屏点睛

    private CSJSplashAd mSplashAd;
    private SplashClickEyeManager mSplashClickEyeManager;
    private CSJSplashAd.SplashClickEyeListener mSplashClickEyeListener;

    private LinearLayout mSplashHalfSizeLayout;

    private FrameLayout mSplashSplashContainer;

    @SuppressWarnings("RedundantCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ImmersionBar.with(this).statusBarColor(R.color.white).transparentStatusBar().transparentNavigationBar().init();

        mSplashContainer = (FrameLayout) findViewById(R.id.splash_container);
        mSplashHalfSizeLayout = (LinearLayout) findViewById(R.id.splash_half_size_layout);
        mSplashSplashContainer = (FrameLayout) findViewById(R.id.splash_container_half_size);

        //step2:创建TTAdNative对象
        mTTAdNative = TTAdManagerHolder.get().createAdNative(this);
//        getExtraInfo();

        if (AppLpds.getMySp().getIsFirst()) {
//            Tt.show(this,"展示");
            agreementDialog();
        } else {
            getAppInfo();
//            if (Build.VERSION.SDK_INT >= 23) {
//                checkAndRequestPermission();
//            } else {
//                getAppInfo();
//            }
        }
    }

    private void agreementDialog() {
        AgreementDialog mDialog = new AgreementDialog(this,
                R.style.recharge_pay_dialog,
                new AgreementDialog.OnDialogEventListener() {

                    @Override
                    public void onClicked(int v) {
                        switch (v) {
                            case 1:
                                WebActivity.start(SplashActivity.this,
                                        "服务协议",
                                        Constants.FUWU);

                                break;
                            case 2:
                                WebActivity.start(SplashActivity.this,
                                        "隐私协议",
                                        Constants.YINSI);
                                break;
                        }
                    }

                    @Override
                    public void onKonw() {
                        AppLpds.getMySp().setIsFirst(false);
//                        goToMainActivity();
//                        AppLpds.getInstance().initThirdParty();
                        getAppInfo();
                    }

                    @Override
                    public void onCancel() {
                        System.exit(0);
//                        MainActivity.this.finish();
                    }
                });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
    }

    private void getAppInfo() {
        OkHttpClient okHttpClient = new OkHttpClient();
//        RequestBody body = new FormBody.Builder()
//                .add("appexpId", Constants.APPEXP_ID)
//                .add("versionCode", AppLpds.getInstance().getVersionCode())
//                .build();
        final Request request = new Request.Builder()
                .url(Constants.BASE_URL + "/api/public/getAppFunction?appId=" + Constants.APP_ID)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    goToMainActivity();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
                Log.i("TAG__", body);
                runOnUiThread(() -> {
                    if (!TextUtils.isEmpty(body)) {
                        try {
                            NetResponse<ADVBean> info = new Gson().fromJson(body, new TypeToken<NetResponse<ADVBean>>() {
                            }.getType());
                            if (null != info && info.getStatusCode() == 200 && info.getData() != null) {
                                if (info.getData().isOpen()) {
                                    AppLpds.getInstance().initAd();
                                    TTAdManagerHolder.start(SplashActivity.this.getApplicationContext());
                                    loadSplashAd();
                                } else {
                                    goToMainActivity();
                                }
                                AppLpds.getInstance().setShowAd(info.getData().isOpen());
                            } else {
                                goToMainActivity();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            goToMainActivity();
                        }
                    } else {
                        goToMainActivity();
                    }
                });
            }
        });
    }

    private void getExtraInfo() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        String codeId = intent.getStringExtra("splash_rit");
        if (!TextUtils.isEmpty(codeId)) {
            mCodeId = codeId;
        }
        mIsExpress = intent.getBooleanExtra("is_express", false);
    }

    @Override
    protected void onResume() {
        //判断是否该跳转到主页面
        if (mForceGoMain) {
            goToMainActivity();
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
//        mForceGoMain = true;
    }

    /**
     * 加载开屏广告
     */
    private void loadSplashAd() {
        SplashClickEyeManager.getInstance().setSupportSplashClickEye(false);
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dm);
        float splashWidthDp = UIUtils.getScreenWidthDp(this);
        int splashWidthPx = UIUtils.getScreenWidthInPx(this);
        int screenHeightPx = UIUtils.getScreenHeight(this);
        float screenHeightDp = UIUtils.px2dip(this, screenHeightPx);
        float splashHeightDp;
        int splashHeightPx;


        if (mIsHalfSize) {
            // 开屏高度 = 屏幕高度 - 下方预留的高度，demo中是预留了屏幕高度的1/5，因此开屏高度传入 屏幕高度*4/5
            splashHeightDp = screenHeightDp * 4 / 5.f;
            splashHeightPx = (int) (screenHeightPx * 4 / 5.f);
        } else {
            splashHeightDp = screenHeightDp;
            splashHeightPx = screenHeightPx;
        }


        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(Constants.ADV_CORED_ID)
                //模板广告需要设置期望个性化模板广告的大小,单位dp,代码位是否属于个性化模板广告，请在穿山甲平台查看
                //view宽高等于图片的宽高
                .setExpressViewAcceptedSize(splashWidthDp, splashHeightDp) // 单位是dp
                .setImageAcceptedSize(splashWidthPx, splashHeightPx) // 单位是px
                .build();

        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理

        final CSJSplashAd.SplashAdListener listener = new SplashAdListener(this, mIsSplashClickEye);

        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.CSJSplashAdListener() {

            @Override
            public void onSplashLoadSuccess(CSJSplashAd ad) {
                if (ad == null) {
                    return;
                }
                mSplashAd = ad;
                if (mIsHalfSize) {
                    mSplashHalfSizeLayout.setVisibility(View.VISIBLE);
                    mSplashAd.showSplashView(mSplashSplashContainer);
                    mSplashContainer.setVisibility(View.GONE);
                } else {
                    mSplashAd.showSplashView(mSplashContainer);
                    mSplashHalfSizeLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onSplashLoadFail(CSJAdError error) {
                Tt.show(SplashActivity.this, error.getMsg());
                goToMainActivity();
            }

            @Override
            public void onSplashRenderSuccess(CSJSplashAd ad) {

                //设置SplashView的交互监听器
                mSplashAd.setSplashAdListener(listener);

                if (ad.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
                    TTAppDownloadListener downloadListener = new SplashDownloadListener();
                    mSplashAd.setDownloadListener(downloadListener);
                }
                //初始化卡片开屏相关数据
                SplashCardManager.getInstance().init(SplashActivity.this, mSplashAd, mSplashAd.getSplashView(), new SplashCardManager.Callback() {
                    @Override
                    public void onStart() {
                        // 当动画开始时回调，您可以在此处理渲染卡片背后的界面等操作
                    }

                    @Override
                    public void onClose() {
                        // 当卡片关闭时回调，您可以在这里处理Activity的关闭操作等
                        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                        startActivity(intent);
                        if (mSplashContainer != null) {
                            mSplashContainer.removeAllViews();
                        }
                        finish();
                    }
                });
                //初始化开屏点睛相关数据
                initSplashClickEyeData(mSplashAd, ad.getSplashView());
            }

            @Override
            public void onSplashRenderFail(CSJSplashAd ad, CSJAdError csjAdError) {
                Tt.show(SplashActivity.this, csjAdError.getMsg());
                goToMainActivity();
            }
        }, AD_TIME_OUT);

    }

    private boolean onJump;

    /**
     * 跳转到主页面
     */
    private void goToMainActivity() {
        if (onJump) {
            return;
        }
        if (!AppLpds.getMySp().getIsFirst()) {
            onJump = true;
            startActivity(new Intent(this, MainActivity.class));
            if (mSplashContainer != null) mSplashContainer.removeAllViews();
            this.finish();
        }
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }

    //    @Override
//    protected void onPause() {
//        super.onPause();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //检测当前APP是否安全
//                if (!AntiHiJack.checkActivity(SplashActivity.this)) {//不安全
//                    runOnUiThread(() -> {
//                        ToastUtils.show("注意，当前APP已在后台运行!");
//                    });
//                }
//            }
//        }).start();
//    }

    private int px2dp(final float pxValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void checkAndRequestPermission() {
        List<String> lackedPermission = new ArrayList<String>();
        if (!(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_PHONE_STATE);
        }
        // 权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {
            getAppInfo();
        } else {
            // 请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限，如果获得权限就可以调用SDK，否则不要调用SDK。
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            requestPermissions(requestPermissions, 1024);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        getAppInfo();
    }

    private void initSplashClickEyeData(CSJSplashAd splashAd, View splashView) {
        if (splashAd == null || splashView == null) {
            return;
        }
        mSplashClickEyeListener = new SplashClickEyeListener(SplashActivity.this, splashAd, mSplashContainer, splashView, mIsSplashClickEye);

        splashAd.setSplashClickEyeListener(mSplashClickEyeListener);
        mSplashClickEyeManager = SplashClickEyeManager.getInstance();
        mSplashClickEyeManager.setCSJSplashInfo(splashAd, splashView, getWindow().getDecorView());
    }

    public static class SplashClickEyeListener implements CSJSplashAd.SplashClickEyeListener {
        private SoftReference<Activity> mActivity;

        private CSJSplashAd mSplashAd;
        private ViewGroup mSplashContainer;
        private boolean mIsFromSplashClickEye = false;
        private View mSplashView;

        public SplashClickEyeListener(Activity activity, CSJSplashAd splashAd, ViewGroup splashContainer, View splashView, boolean isFromSplashClickEye) {
            mActivity = new SoftReference<>(activity);
            mSplashAd = splashAd;
            mSplashContainer = splashContainer;
            mSplashView = splashView;
            mIsFromSplashClickEye = isFromSplashClickEye;
        }

        private void finishActivity() {
            if (mActivity.get() == null) {
                return;
            }
            mActivity.get().finish();
        }

        private void startSplashAnimationStart(final CSJSplashAd bean) {
            if (mActivity.get() == null || bean == null || mSplashContainer == null) {
                return;
            }

            if (!mIsFromSplashClickEye) {
                return;
            }
            SplashClickEyeManager splashClickEyeManager = SplashClickEyeManager.getInstance();
            splashClickEyeManager.startSplashClickEyeAnimation(mSplashView, mSplashContainer, new SplashClickEyeManager.AnimationCallBack() {
                @Override
                public void animationStart(int animationTime) {
                }

                @Override
                public void animationEnd() {
                    bean.showSplashClickEyeView(mSplashContainer);
                    SplashClickEyeManager.getInstance().clearCSJSplashStaticData();
                }
            });
        }

        @Override
        public void onSplashClickEyeReadyToShow(CSJSplashAd bean) {
            Log.d("CSJSplashActivity", "onSplashClickEyeCanShow ");
            SplashClickEyeManager splashClickEyeManager = SplashClickEyeManager.getInstance();
            splashClickEyeManager.setSupportSplashClickEye(true);
            //开始执行开屏点睛动画
            startSplashAnimationStart(bean);
        }

        @Override
        public void onSplashClickEyeClick() {
            Log.d("CSJSplashActivity", "onSplashClickEyeClick 点睛点击");
        }

        @Override
        public void onSplashClickEyeClose() {
            Log.d("CSJSplashActivity", "onSplashClickEyeClose");
            //sdk关闭了了点睛悬浮窗
            SplashClickEyeManager splashClickEyeManager = SplashClickEyeManager.getInstance();
            boolean isSupport = splashClickEyeManager.isSupportSplashClickEye();
            if (mIsFromSplashClickEye && isSupport) {
                finishActivity();
            }
            splashClickEyeManager.clearCSJSplashStaticData();
        }
    }

    public static class SplashAdListener implements CSJSplashAd.SplashAdListener {

        public WeakReference<Activity> mContextRef;
        private boolean mIsSplashClickEye;

        public SplashAdListener(Activity activity, boolean isSplashClickEye) {
            mContextRef = new WeakReference<>(activity);
            mIsSplashClickEye = isSplashClickEye;
        }

        private void showToast(Context context, String msg) {
            if (context == null || TextUtils.isEmpty(msg)) {
                return;
            }
//            Tt.show(context,msg);
        }

        private void goToMainActivity(boolean isSplashClickEye) {
            if (mContextRef.get() == null) {
                return;
            }
            if (SplashCardManager.getInstance().canShowInnerActivityCard()) {
                return;
            }
            boolean isSupport = SplashClickEyeManager.getInstance().isSupportSplashClickEye();

            //TODO:是否指支持一种，这里主要两个作用一个是是否关闭开屏，是否清除数据
            if (isSplashClickEye) {
                if (isSupport) {
                    return;
                } else {
                    SplashClickEyeManager.getInstance().clearCSJSplashStaticData();
                }
            }
            Intent intent = new Intent(mContextRef.get(), MainActivity.class);
            mContextRef.get().startActivity(intent);
            mContextRef.get().finish();
        }

        @Override
        public void onSplashAdShow(CSJSplashAd ad) {
            Log.d(TAG, "onAdShow");
            showToast(mContextRef.get(), "开屏广告展示");
        }

        @Override
        public void onSplashAdClick(CSJSplashAd ad) {
            Log.d(TAG, "onAdClicked");
            showToast(mContextRef.get(), "开屏广告点击");
        }

        @Override
        public void onSplashAdClose(CSJSplashAd ad, int closeType) {
            if (closeType == CSJSplashCloseType.CLICK_SKIP) {
                showToast(mContextRef.get(), "开屏广告点击跳过 ");
            } else if (closeType == CSJSplashCloseType.COUNT_DOWN_OVER) {
                showToast(mContextRef.get(), "开屏广告点击倒计时结束");
            } else if (closeType == CSJSplashCloseType.CLICK_JUMP) {
                showToast(mContextRef.get(), "点击跳转");
            }
            goToMainActivity(mIsSplashClickEye);
        }
    }

    public static class SplashDownloadListener implements TTAppDownloadListener {
        private boolean hasShow = false;

        @Override
        public void onIdle() {

        }

        @Override
        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
            if (!hasShow) {
                Log.d(TAG, "下载中...");
                hasShow = true;
            }
        }

        @Override
        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
            Log.d(TAG, "下载暂停...");
        }

        @Override
        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
            Log.d(TAG, "下载失败...");
        }

        @Override
        public void onDownloadFinished(long totalBytes, String fileName, String appName) {
            Log.d(TAG, "下载完成...");
        }

        @Override
        public void onInstalled(String fileName, String appName) {
            Log.d(TAG, "安装完成...");
        }
    }

}
